using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using server.Models;
using server.Services;


namespace server.Controllers;

public class TokenFilterAttribute : Attribute, IActionFilter{
    private Right target_right=Right.None;
    // private TokenService tokenService;

    public TokenFilterAttribute(Right target)
    {
        // this.tokenService=service;
        target_right=target;
    }
        public void OnActionExecuting(ActionExecutingContext context)
    {
        var headers=context.HttpContext.Request.Headers;
        var uid_str=headers["X-UID"];
        var token=headers["X-Token"];
        if (String.IsNullOrEmpty(uid_str) || String.IsNullOrEmpty(token))
        {
            context.Result=new ContentResult{
                StatusCode=403,
                Content="No token or uid found in headers!"
            };            
            return;
        }
        if (!int.TryParse(uid_str,out int uid) || !long.TryParse(token,out long token_id))
        {
            context.Result=new ContentResult{
                StatusCode=403,
                Content="Invalid uid or token formation!"
            };
            return;
        }
        var token_service=context.HttpContext.RequestServices.GetService<TokenService>();
        if (!token_service!.ValidateToken(uid,token_id,target_right))
        {
            context.Result=new ContentResult{
                StatusCode=401,
                Content="Invalid token!"
            };
            return;
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // Do something after the action executes.
    }
}